package main
import (
	"fmt"
)

func main(){
	numchan := make(chan int,2000) //数字管道
	exitchan := make(chan bool,8)	//判断是否结束主线程管道
	reschan := make(chan string,2000) //结果管道
	go PutNumber(numchan)
	for i:=0;i<8;i++{   //大大提升cpu利用率
		go GetResult(reschan,numchan,exitchan)
	}
	go func(){
		for i:=1;i<=8;i++{  //等待8个协程跑完在继续往下执行
			v :=<-exitchan
			fmt.Printf("第%d协程跑完了吗？%v\n",i,v)
		}
		close(reschan)
	}()
	for t := range reschan{
		fmt.Printf("%v ",t)
	}
}

func PutNumber(numchan chan int){
	for i:=1;i<= 2000;i++{
		numchan <- i
		fmt.Printf("放入数据%v到numchan\n",i)
	}
	close(numchan) //数据放完就关闭管道，不在放入
}

func GetResult(reschan chan string,numchan chan int,exitchan chan bool){
	for {
		n,ok := <- numchan
		if !ok{  //管道没数据了就退出
			break
		}
		res := 0
		for i:=1;i<=n;i++{
			res += i
		}
		str := fmt.Sprintf("res[%d]=[%d]",n,res)
		reschan <- str
	}
	exitchan <- true   //本协程已经取不到数了就退出，并且存入一个true
}